<?php	
namespace app\pay\controller\common;

use think\Controller;
use customtool\Utils;

class Fee extends Base {
    /*
     * 代付手续费返还
     * @params  $id->model('PayDaifuApply')表中的id
     */
    public function refund() {
        $data = input('post.');
        $mod = array( // 必传参数
            0 => 'id',
            1 => 'fee'
        );
        $resParams = Utils::checkParamsExists($data, $mod, null);
        if($resParams) {
            return $this->feeHandle($data);
        } else {
            return $resParams;
        }
    }
    
    private function feeHandle($data) {
        $id  = $data['id'];
        $fee = $data['fee'];
        if(preg_match("/^[1-9][0-9]*$/", $fee)) {
            // 根据商户号获取商户相关信息
            $resPayDaifuApply = model('PayDaifuApply')->get(['id' => $id]);
            if($resPayDaifuApply) {
                if($resPayDaifuApply->refund_fee > 0) {
                    return retMsgFalse('手续费已退回，请勿重复操作');
                }
                $resPayBis = model('PayBis')->get(['merchant_id' => $resPayDaifuApply->merchant_id]);
                if($resPayBis->is_prepay == 0) {
                    $payBisData['platform_amount'] = $resPayBis->platform_amount + $fee;
                    $payBisData['amount'] = $resPayBis->amount + $fee;
                    $payBisData['refund_fee'] = $fee;
                }
                if($resPayBis->is_prepay == 1) {
                    $payBisData['platform_amount'] = $resPayBis->platform_amount + $fee;
                    $payBisData['mchnt_pre_fee'] = $resPayBis->mchnt_pre_fee + $fee;
                    $payBisData['refund_fee'] = $fee;

                }
                $ret = model('PayBis')->updateById($payBisData, $resPayBis->id);
                if($ret) {
                    return retMsgTrue('手续费退回操作成功');
                } else {
                    return retMsgFalse('手续费退回操作失败');
                }
              } else {
                // 商户号不存在
                return paymchntIdFalse();
            }
        }  else {
            return retMsgFalse('手续费必须是大于0的整数(分)');
        }
    }
}